package org.example.service.tree.impl;

import org.example.service.tree.TreeContentProvider;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;

import java.util.ArrayList;
import java.util.List;

public class HtmlTreeContentProvider implements TreeContentProvider<Node> {

    private Document document;

    public HtmlTreeContentProvider(Document document) {
        this.document = document;
    }

    @Override
    public List<Node> getRoots() {
        return List.of(this.document.child(0));  // 从 <html> 根节点开始
    }

    @Override
    public List<Node> getChildren(Node node) {
        List<Node> children = new ArrayList<>();

        // 遍历节点的所有子节点，包括文本节点
        for (Node childNode : node.childNodes()) {
            if (childNode instanceof Element) {
                children.add(childNode);
            } else if (childNode instanceof TextNode) {
                TextNode textNode = (TextNode) childNode;
                String text = textNode.text().trim();
                if (!text.isEmpty()) {
                    children.add(textNode);
                }
            }
        }
        return children;
    }
}
